package net.lesscoding.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.shop.common.Result;
import net.lesscoding.shop.entity.Goods;
import net.lesscoding.shop.entity.GoodsNumberLog;
import net.lesscoding.shop.enums.ShopCode;
import net.lesscoding.shop.exception.CastException;
import net.lesscoding.shop.mapper.GoodsMapper;
import net.lesscoding.shop.mapper.GoodsNumberLogMapper;
import net.lesscoding.shop.service.GoodsService;
import net.lesscoding.shop.utils.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
* @author 24962
* @description 针对表【trade_goods】的数据库操作Service实现
* @createDate 2024-06-07 15:16:06
*/
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsNumberLogMapper logMapper;

    /**
     * 实际开发记得考虑并发
     * @param goodsLog
     * @return
     */
    @Override
    public Result reduceGoodsNum(GoodsNumberLog goodsLog) {
        if (notValidLog(goodsLog)) {
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        Goods goods = getById(goodsLog.getGoodsId());
        if (BigDecimalUtil.lessThan(goods.getGoodsNumber(), goodsLog.getGoodsNumber())) {
            CastException.cast(ShopCode.SHOP_GOODS_NUM_NOT_ENOUGH);
        }
        goods.setGoodsNumber(goods.getGoodsNumber() - goodsLog.getGoodsNumber());
        goodsMapper.updateById(goods);

        goodsLog.setGoodsNumber(-goods.getGoodsNumber());
        goodsLog.setLogTime(LocalDateTime.now());
        logMapper.insert(goodsLog);
        log.info("订单{}扣减库存日志记录完成", goodsLog.getOrderId());
        return Result.success(true);
    }

    private boolean notValidLog(GoodsNumberLog log) {
        return log == null ||
                log.getGoodsId() == null ||
                log.getOrderId() == null ||
                log.getGoodsNumber() <= 0;
    }
}




